package com.sunmouse.toolkit.service;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.v7.app.NotificationCompat;

import com.sunmouse.toollib.utils.LogUtils;
import com.sunmouse.toollib.utils.ToastUtils;
import com.sunmouse.toolkit.R;
import com.sunmouse.toolkit.activity.ContentActivity;
import com.sunmouse.toolkit.constant.Config;
import com.sunmouse.toolkit.util.PageUtil;

import java.util.Timer;
import java.util.TimerTask;

public class PushService extends Service {
    private Timer mTimer;
    private PushService mService;
    private NotificationManager mManager;

    public PushService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mTimer = new Timer();
        mService = this;
        mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        ToastUtils.simpleToast(this, "Service launched...");
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");


    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mTimer.schedule(new PushTask(), 0, 3 * 1000);
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * push task
     */
    private class PushTask extends TimerTask {
        private int count;

        @Override
        public void run() {
            count++;
            Intent mIntent = new Intent(getService(), ContentActivity.class);
            mIntent.putExtra(Config.Key.INDEX, PageUtil.Index.CHAT);
            PendingIntent mPending = PendingIntent.getActivity(getService(), 5, mIntent, PendingIntent.FLAG_ONE_SHOT);
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getService());
            mBuilder.setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("ToolKit")
                    .setAutoCancel(true)   //cancel if user click it
                    .setContentText("[" + count + "]" + " new message")
                    .setContentIntent(mPending)
            ;
            mManager.notify(1, mBuilder.build());
            LogUtils.d("------count=" + count);
        }
    }

    /**
     * used in other class or inner class
     *
     * @return
     */
    protected Service getService() {
        return this;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mTimer != null) {
            mTimer.cancel();
            mTimer.purge();
            mTimer = null;
        }
//        LogUtils.d("-------------service--destroy");
    }
}
